﻿using System;
using System.Text.RegularExpressions;
using UnityEngine;

[DisallowMultipleComponent]
public class NumChoose : MonoBehaviour
{
    public GameObject m_LeftBtn;
    public GameObject m_RightBtn;
    public UIInput m_InputTxt;
    public Action<int> OnChange;

    private bool mIsLoop;
    private int minValue;
    private int stepValue;

    int charCount = 9;
    int maxVaue = 1;
    int curValue = 1;

    void Awake()
    {
        if (m_LeftBtn && m_RightBtn)
        {
            UIEventListener.Get(m_LeftBtn).onClick = OnEventClick;
            UIEventListener.Get(m_RightBtn).onClick = OnEventClick;
        }
        if (m_InputTxt != null)
        {
            m_InputTxt.onSubmit.Add(new EventDelegate(OnSubmit));
        }
    }

    public void SetData(int curValue, int maxVaue, int minValue = 1, int stepValue = 1, bool mIsLoop = false)
    {
        if (curValue < 0 || maxVaue < 0 || minValue < 0 || stepValue < 0) { return; }

        this.curValue = curValue;
        this.maxVaue = maxVaue;
        this.minValue = minValue;
        this.stepValue = stepValue;
        this.mIsLoop = mIsLoop;
    }

    void OnSubmit()
    {
        bool result = Regex.IsMatch(m_InputTxt.value, "^([1-9][0-9]*)$");
        if (!result || m_InputTxt.value.Length > charCount)
        {
            curValue = minValue;
        }
        else { curValue = int.Parse(m_InputTxt.value); }

        if (curValue < minValue)
        {
            curValue = maxVaue;
        }
        else if (curValue > maxVaue)
        {
            curValue = minValue;
        }
        if (OnChange != null) { OnChange(curValue); }
    }

    void OnEventClick(GameObject go)
    {
        if (go == m_LeftBtn)
        {
            curValue -= stepValue;
            if (curValue < minValue)
            {
                if (mIsLoop) { curValue = maxVaue; }
                else { curValue = minValue; }
            }
        }
        else if (go == m_RightBtn)
        {
            curValue += stepValue;
            if (curValue > maxVaue)
            {
                if (mIsLoop) { curValue = minValue; }
                else { curValue = maxVaue; } 
            }
        }
        if (OnChange != null) { OnChange(curValue); }
    }

    public void OpenInput(bool isOpen)
    {
        if (m_InputTxt != null) { m_InputTxt.enabled = isOpen; }
    }

    public void SetInputTxt(string strInput)
    {
        if (m_InputTxt != null) { m_InputTxt.value = strInput; }
    }

    public void SetBtnState(bool left, bool right)
    {
        Utility.SetActive(m_LeftBtn, left);
        Utility.SetActive(m_RightBtn, right);
    }
}